<!-- 接搜两个参数一个是关注状态is_followed，一个是用户idaut_id -->
<template>
  <div class="following-box">
    <van-button
      :class="f2 ? 'follow-btn2' : 'follow-btn'"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      v-if="!is_followed"
      @click="onFollowed"
      :loading="btnLoading"
      >关注</van-button
    >
    <van-button
      class="follow-btn"
      round
      size="small"
      @click="quitFollowed"
      :loading="btnLoading"
      v-else
      >已关注</van-button
    >
  </div>
</template>

<script>
// 导入关注api和取消关注
import { followings, quitFollowings } from '@/assets/api/user.js'
// 导入vuex的user
import { mapState } from 'vuex'
export default {
  name: 'follow-btn',
  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    aut_id: {
      type: [Number, String, Object],
      required: true
    },
    f2: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 按钮加载
      btnLoading: false
    }
  },
  methods: {
    async onFollowed() {
      // 判断用户是否登入
      if (!this.user) {
        return this.$toast('请登入')
      }
      try {
        this.btnLoading = true
        // 发起请求关注用户
        var { data: res } = await followings(this.aut_id)
      } catch (err) {
        // 处理请求失败
        let message = '关注失败请稍后重试'
        if (err.response && err.response.status === 400) {
          message = '不能关注自己'
        }
        return this.$toast.fail(message)
      }
      // 将关注状态保存值本地
      this.btnLoading = false
      this.$emit('toFollowed')
    },
    // 取消关注功能
    async quitFollowed() {
      // 判断用户是否登入
      if (!this.user) {
        return this.$toast('请登入')
      }
      try {
        // 发起请求取消关注用户
        this.btnLoading = true
        var { data: res } = await quitFollowings(this.aut_id)
      } catch {
        // 处理请求失败
        return this.$toast.fail('取消关注失败请稍后重试')
      }
      // 将关注状态保存值本地
      this.btnLoading = false
      this.$emit('quitFollowed')
    }
  },
  computed: {
    ...mapState(['user'])
  }
}
</script>

<style lang="less" scoped>
.follow-btn {
  width: 170px;
  height: 58px;
}
.follow-btn2 {
  width: 290px;
  height: 56px;
  border-radius: 10px;
}
</style>
